<?php
/**
 * CreateTime: 2023/7/13 11:45
 */

namespace App\Http\Controllers\Login;

use App\Func\EncryptionFunc;
use App\Func\RequestFunc;
use App\Func\ResponseFunc;
use App\Http\pkConfig\login\PkLoginConfigGet;
use App\Http\Requests\Login\AdminLoginRequest;
use App\Models\AdminStaff\AdminStaffModel;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Redis;


class AdminLoginController
{
    public function adminLogin(AdminLoginRequest $request){
        $adminLoginPkConfig = new PkLoginConfigGet();
        $encryptionFunc = new EncryptionFunc();
        $data = $request->all();
        $aseKey = $encryptionFunc->rsaToBase64Decode($adminLoginPkConfig->getPrKey(),$data['sign']);
        if(!$aseKey){
            return ResponseFunc::returnJson(
                'error',
                null,
                "签名验证失败",
                200
            );
        }

        // 解析账号密码
        $account = $encryptionFunc->Aes256cbcPkcs7ToBase64Decode($aseKey,$data['root_account']);
        $root_password = $encryptionFunc->Aes256cbcPkcs7ToBase64Decode($aseKey,$data['root_password']);

        // 查询管理员账号
        $adminStaffModel = new AdminStaffModel();
        $adminStaffInfo = $adminStaffModel->getAdminStaffInfoByAdminAccount($account);
        if(!$adminStaffInfo){
            return ResponseFunc::returnJson(
                'error',
                null,
                "账号或密码不匹配",
                200
            );
        }
        // 校验两个密码加密后是否一致
        if (!(Hash::check($root_password, $adminStaffInfo['password']))) {
            // 密码验证失败
            return ResponseFunc::returnJson(
                'error',
                null,
                "账号或密码不匹配",
                200
            );
        }
        // 刷新最后登录日期
        $adminStaffInfo->where('admin_id',$adminStaffInfo['admin_id'])->update([
            'last_login_time' => date("Y-m-d h:i:s",time())
        ]);

        // 根据IP_时间_用户名生成token
        $ip = RequestFunc::getIP();
        # adx路由下的 login 调解中心话务员
        $tokenStr = "adx_lg_mediation_admin_v2_".$adminStaffInfo['admin_id'];
        $tokenEncryptionStr = $encryptionFunc->rsaToBase64Encode($adminLoginPkConfig->getPuKey(),$tokenStr);
        $tokenValue = [
            'admin_info' => $adminStaffInfo->toArray(),
            'ip' => $ip,
        ];
        // 过期时间设置的一个小时
        $code = Redis::setex($tokenStr,3600,serialize($tokenValue));
         return ResponseFunc::returnJson(
            'ok',
            [
                'token' => $tokenEncryptionStr
            ],
            "登录成功",
            200
        );
    }
}